let webSocket;
const app = getApp();
let connected =false;
let connectIng =false;


export default {
  /**
   * 链接服务器
   * @param {用户id}} userId 
   */
  connectServer(userId) {
    if(connectIng){return}
    userId=userId || app.globalData.myUserInfo.id

    /**
     * 链接成功
     */
    wx.onSocketOpen((result) => {
      connected=true;
      wx.event.emit("socket-events",{"status":0,"msg":"connected"})
      wx.onSocketMessage((result) => {
        let data = JSON.parse(result.data);
        wx.event.emit("socket-msg",{"status":-1,"data":data})
      })
    })
    wx.onSocketClose((result) => {
      connected=false;
      connectIng=false;
      wx.event.emit("socket-events",{"status":-1,"msg":"服务器连接失败，正在重试"})
    })
    wx.onSocketError((result) => {
      connected=false;
      connectIng=false;
      wx.hideLoading({
        complete: (res) => {},
      })
      wx.event.emit("socket-events",{"status":-1,"msg":"服务器连接失败，正在重试"})
    })
   let socketTask =  wx.connectSocket({
      url: app.globalData.WEB_SOCKET_ADDRESS.concat(userId),
    })
    connectIng=true;
    
  },

  sendMessage(message) {
    wx.sendSocketMessage({
      data: message,
    })
  },
  recvMessage() {
    wx.onSocketMessage((result) => { })
  },
  isConnect(){
    return connected
  }
}